package com.cssw.fyzb.busi.api.auth;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cssw.fyzb.busi.config.TpsClient;
import com.cssw.fyzb.busi.service.user.DistrictService;
import com.cssw.fyzb.busi.service.user.UserService;
import com.cssw.fyzb.busi.util.BizUtil;
import com.cssw.fyzb.busi.util.UuidUtil;
import com.cssw.fyzb.core.dao.user.vo.AuthInfoVo;
import com.cssw.fyzb.core.exception.BizException;
import com.cssw.fyzb.core.model.dodb.CmfUser;
import com.cssw.fyzb.core.model.dodb.District;
import com.cssw.fyzb.core.model.dodb.User;
import com.cssw.fyzb.core.util.StringUtil;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import com.ydn.simplecache.SimpleCache;
import com.ydn.simplelock.SimpleLockFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;

/**
 * 后台送身份信息
 *
 * @Author zhouxu
 * @create 2020-09-15 20:48
 */
@Function(description = "后台送身份信息", parameters = {
        @Parameter(name = "userId", type = Type.Integer, description = "用户编号", required = true),
        @Parameter(name = "userName", type = Type.Integer, description = "姓名", required = true),
        @Parameter(name = "idCard", type = Type.Integer, description = "身份证", required = true),
        @Parameter(name = "districtCode", type = Type.Integer, description = "区县", required = false),
        @Parameter(name = "cityCode", type = Type.Integer, description = "市", required = true),
        @Parameter(name = "provinceCode", type = Type.Integer, description = "省", required = true),

})
@Component
public class TecentFaceAuthSend implements Action {

    private static final Logger logger = LoggerFactory.getLogger(TecentFaceAuthSend.class);

    @Autowired
    private UserService userService;

    @Autowired
    private TpsClient tpsClient;

    @Autowired
    private SimpleCache simpleCache;

    @Autowired
    private SimpleLockFactory simpleLockFactory;

    @Autowired
    private DistrictService districtService;

    @Override
    public Response execute(Request request) throws Exception {
        Long userId = request.getLong("userId");
        String districtCode = request.getString("districtCode");
        String cityCode = request.getString("cityCode");
        String provinceCode = request.getString("provinceCode");

        User user = userService.getById(userId);
        if (user == null) {
            return Response.fail("未找到用户");
        }
        //先认证在支付
        /*if(!user.isPayAuth()){
            return Response.fail("请先支付实名费用");
        }*/
        String idNo = request.getString("idCard");
        // 一人一号判断
//        if (userService.getAuthUserById(idNo) != null) {
//            return Response.fail("身份证已实名，无法重复实名");
//        }
        User userIdCard = userService.getIdCard(idNo);
        if (userIdCard != null) {
            return Response.fail("身份证已实名，无法重复实名");
        }
        String userName = request.getString("userName");
        String orderNo = UuidUtil.getNoSpecialChar();
        String nonceStr = UuidUtil.getNoSpecialChar();// 送前端
        logger.info(orderNo);

        //更新实名信息到用户
        // userService.saveAuthInfo(userId, userName, provinceCode, cityCode, districtCode, idNo);

        // 地区名称
        District district = districtService.getByCode(provinceCode);
        if (district == null) {
            BizUtil.exception("省份信息不正确");
        }

        // 城市名称
        district = districtService.getByCode(cityCode);
        if (district == null) {
            BizUtil.exception("城市信息不正确");
        }

        //存redis
        AuthInfoVo vo = new AuthInfoVo();
        vo.setUserId(userId);
        vo.setUserName(userName);
        vo.setProvinceCode(provinceCode);
        vo.setCityCode(cityCode);
        vo.setDistrictCode(districtCode);
        vo.setIdNo(idNo);
        simpleCache.put("AUTHINFOVO" + userId, JSON.toJSONString(vo), 4 * 60 * 60);

        Map<String, Object> data = new HashMap<>();
        data.put("orderNo", orderNo);
        data.put("nonce", nonceStr);
        data.put("userId", String.valueOf(userId));

        try {
            // 记录认证日志
            userService.saveAuthRecord(userId, userName, idNo, provinceCode, cityCode, districtCode);

            // 调用第三方进行验证
            data.putAll(sendUserInfo(userId, userName, idNo, orderNo, nonceStr));
            return Response.success().put("data", data);
            // 记录日志
        } catch (Exception e) {
            if (e instanceof BizException) {
                BizException be = (BizException) e;
                return Response.fail(be.getErrMsg(), be.getErrCode());
            }
            logger.error("异常信息", e);
            return Response.fail(e);
        }

    }


    private Map<String, String> sendUserInfo(Long userId, String userName, String idNo, String orderNo, String nonceStr) {
        Request request = new Request("TecentFaceAuthSend");
        request.setParameter("userId", userId);
        request.setParameter("userName", userName);
        request.setParameter("idNo", idNo);
        request.setParameter("nonceStr", nonceStr);
        request.setParameter("orderNo", orderNo);
        Response response = tpsClient.send(request);
        String msg = response.getOriginalJson();
        if (null != msg && msg.length() > 180) {
            msg = msg.substring(0, 180);
        }
        logger.debug(response.getMessage());
        // 异常信息处理
        if (!response.isSuccess()) {
            userService.saveSendAuthFaceFail(
                    orderNo, nonceStr, String.valueOf(response.getCode()),
                    msg, userId, userName, idNo
            );

            throw new BizException(response.getCode(), response.getMessage());
        }
        userService.saveSendAuthFaceSucc(
                orderNo, nonceStr, String.valueOf(response.getCode()),
                msg, userId, userName, idNo
        );
        return parseJson(response.getOriginalJson());
    }

    private Map<String, String> parseJson(String json) {
        Map<String, String> param = new HashMap<>();
        JSONObject jsonObject = JSON.parseObject(json);
        JSONObject dataObject = jsonObject.getJSONObject("data");
        String sign = dataObject.getString("sign");
        String license = dataObject.getString("license");
        String appId = dataObject.getString("appId");
        String version = dataObject.getString("version");
        JSONObject dataObject2 = dataObject.getJSONObject("data");
        JSONObject dataObject3 = dataObject2.getJSONObject("data");
        String bizSeqNo = dataObject3.getString("bizSeqNo");
        String faceId = dataObject3.getString("faceId");
        String orderNo = dataObject3.getString("orderNo");

        param.put("version", version);
        param.put("license", license);
        param.put("sign", sign);
        param.put("bizSeqNo", bizSeqNo);
        param.put("faceId", faceId);
        param.put("orderNo", orderNo);
        param.put("appId", appId);
        return param;
    }


}
